<template>
  <div class="tab-panel">
    <!--工具栏-->
    <el-form ref="query" :inline="true" :model="query" size="small" class="demo-form-inline" label-position="right">
      <el-form-item label="统计时间:">
        <el-date-picker
          v-model="query.time"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd HH:mm"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
          style="width:360px"/>
      </el-form-item>
      <el-form-item label="关键词:">
        <el-input
          v-model="query.name"
          placeholder="手机号/微信昵称/姓名"
          clearable
          class="filter-item"
          @keyup.enter.native="toQuery"
        />
      </el-form-item>
      <el-form-item label="邀请人:">
        <el-input
          v-model="query.invite_id"
          placeholder="邀请人编号"
          clearable
          class="filter-item"
          @keyup.enter.native="toQuery"
        />
      </el-form-item>
      <el-form-item label="等级角色:">
        <el-select
          v-model="query.member_type"
          clearable
          class="filter-item"
          style="width: 200px"
        >
          <el-option
            v-for="(item,key) in queryMemberOptions"
            :key="key"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          class="filter-item"
          size="mini"
          icon="el-icon-refresh"
          @click="reset">重置</el-button>
        <el-button
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-search"
          @click="toQuery"
        >查询</el-button>
      </el-form-item>

    </el-form>
    <!-- 操作栏 -->
    <div class="operate-container">
      <div />
      <div>
        <el-button
          :loading="exportSearchLoading"
          class="filter-item"
          type="primary"
          size="mini"
          @click="exportSearch"
        >导出（查询）</el-button>
        <el-button
          :loading="exportCheckedLoading"
          :disabled="$refs.table && $refs.table.selection.length === 0"
          class="filter-item"
          type="warning"
          size="mini"
          @click="exportChecked"
        >导出（勾选）</el-button>
      </div>
    </div>
    <!--表格渲染-->
    <el-table v-loading="loading" ref="table" :data="data" :fit="true" stripe size="small">
      <el-table-column type="selection"/>
      <el-table-column prop="user_id" min-width="120px" label="用户编码"/>
      <el-table-column prop="phone" min-width="120px" label="手机号码"/>
      <el-table-column prop="nick_name" min-width="120px" label="微信昵称"/>
      <el-table-column prop="name" label="姓名"/>
      <el-table-column prop="invite_id" min-width="120px" label="邀请人"/>
      <el-table-column min-width="120px" label="等级角色">
        <template slot-scope="scope">
          <span v-if="scope.row.member_type == 0">客户</span>
          <span v-if="scope.row.member_type == 1">推广员</span>
          <span v-else-if="scope.row.member_type == 2">团长</span>
          <span v-else-if="scope.row.member_type == 3">省长</span>
        </template>
      </el-table-column>
      <el-table-column prop="lower_level_invitation" min-width="120px" label="下级推广数"/>
      <el-table-column prop="own_invitation" min-width="98px" label="自己推广数"/>
      <el-table-column prop="own_apply" min-width="98px" label="自己申请数"/>
      <el-table-column prop="invitation_income" min-width="120px" label="推广收益"/>
      <el-table-column prop="score" min-width="130px" label="当前余额"/>
    </el-table>
    <!--分页组件-->
    <el-pagination
      v-if="showPage"
      :total="total"
      :current-page="page + 1"
      background
      layout="total, prev, pager, next, sizes ,jumper"
      @size-change="sizeChange"
      @current-change="pageChange"
    />
  </div>
</template>

<script>
import initData from '@/mixins/initData'
import { parseTime, parseDate, downLoadExcel } from '@/utils/index'
import { exportOrderCommission } from '@/api/distributionStatistics'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'OrderCommission',
  components: { Treeselect },
  mixins: [initData],
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      menus: [],
      company_show: true,
      queryOrderDate: [new Date().setHours(0, 0, 0, 0), new Date()],
      loading: false,
      dialog: false,
      query: {
        name: '',
        time: '',
        invite_id: '',
        member_type: ''
      },
      queryMemberOptions: [
        { value: '1', name: '分销员' },
        { value: '2', name: '团长' },
        { value: '3', name: '省长' }
      ],
      exportSearchLoading: false,
      exportCheckedLoading: false
    }
  },
  created() {
    if (this.$route.query.create_time) {
      this.queryOrderDate = JSON.parse(this.$route.query.queryOrderDate)
    } else {
      this.queryOrderDate = [new Date().setHours(0, 0, 0, 0), new Date()]
      this.$route.query.create_time = parseTime(new Date().setHours(0, 0, 0, 0)) + '~' + parseTime(new Date())
    }
    if (this.company_id === 443 || this.company_id === 102) {
      this.company_show = false
    }
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    parseTime,
    created() {
      const today = new Date()
      this.queryOrderDate = [today, today]
      this.$nextTick(() => {
        this.init()
      })
    },
    formatMoney(row, column, cellValue, index) {
      return cellValue.toFixed(2)
    },
    countTotal(v1, v2, v3) {
      return v1 + v2 + v3
    },
    beforeInit() {
      this.url = '/api/distribution-statistics'
      this.addParams()
      return true
    },
    addParams() {
      const query = this.query
      this.params = { page: this.page, size: this.size }
      // 查询条件拼接
      const name = query.name
      const inviter_id = query.inviter_id
      const member_type = query.member_type
      const equity = query.equity
      const time = query.time
      if (name !== '' && name !== undefined) {
        this.params['name'] = name
      }
      if (inviter_id !== '' && inviter_id !== undefined) {
        this.params['inviter_id'] = inviter_id
      }
      if (member_type !== '' && member_type !== undefined) {
        this.params['member_type'] = member_type
      }
      if (equity !== '' && equity !== undefined) {
        this.params['equity'] = equity
      }
      if (time !== '' && time !== undefined) {
        this.params['time'] = time.join('~')
      }
    },
    formatOrderTime(timeStamp) {
      const orderTime = new Date(Number(timeStamp))
      return parseDate(orderTime, true)
    },
    formatMemberType(row, column, cellValue, index) {
      return cellValue === 0 ? '非店主' : cellValue === 1 ? '店主' : ''
    },
    formatResultState(row, column, cellValue, index) {
      if (cellValue === 0) {
        return '未结算'
      } else if (cellValue === 1) {
        return '已结算'
      } else {
        return ''
      }
    },
    formatCreateTime(timeStamp) {
      const creatTime = new Date(Number(timeStamp))
      return parseDate(creatTime, true)
    },
    reset() {
      this.query = {}
      this.queryOrderDate = [new Date().setHours(0, 0, 0, 0), new Date()]
      this.init()
    },
    getSelected() {
      const order_nos = []
      const selectArr = this.$refs.table.selection
      for (let i = 0; i < selectArr.length; i++) {
        order_nos.push(selectArr[i].order_no)
      }
      return order_nos
    },
    // 导出勾选
    exportChecked() {
      this.exportCheckedLoading = true
      const order_nos = this.getSelected()
      this.params = { order_nos: order_nos.join(',') }
      exportOrderCommission(this.params).then((res) => {
        this.exportCheckedLoading = false
        downLoadExcel(res, '分销员列表.xlsx')
      }).catch(err => {
        this.exportCheckedLoading = false
        console.log(err)
      })
    },
    // 导出查询
    exportSearch() {
      this.exportSearchLoading = true
      this.addParams()
      exportOrderCommission(this.params).then((res) => {
        this.exportSearchLoading = false
        downLoadExcel(res, '分销员列表.xlsx')
      }).catch(err => {
        this.exportSearchLoading = false
        console.log(err)
      })
    }
  }
}
</script>

<style scoped lang="scss">
  .tab-panel{
    padding:20px;
    margin-top: 10px;
    background-color: #ffffff;
  }
</style>
